import os
from os.path import join, getsize

class PatchUtil:
	root_path = '/home/fkong/cvsroot/consult/mainline/projects/PA'
	problemdb_url = 'http://problem.corp.platform.com/cgi-bin/problemEnh/detail?problem='
	problemdb_search_url = 'http://problem.corp.platform.com//cgi-bin/problemEnh/query'

	def print_list(self):
		patch_ids = self.get_patch_ids()
		for patch_id in patch_ids:
			print('------------------------------------------------------------')
			print('Patch: ' + str(patch_id))
			print('Description:')
			patch_desc_file = self.root_path + '/' + str(patch_id) + '/patch_install/fixlist.db'
			if os.path.exists(patch_desc_file):
				content = ''
				f = open(patch_desc_file)
				for line in f:
					content += line
				f.close()
				print(content)
			else:
				print('Unknown')

	def print_html(self):
		patch_ids = self.get_patch_ids()
		html = ''
		html += '<html>'
		html += '<head></head>'
		html += '<body>'
		html += '<form method="post" action="' + self.problemdb_search_url + '" target="_blank">'
		html += '<input name="Number" value="' + self.generate_patch_id_list(patch_ids) + '" style="display: none;"/>'
		html += '<a href="#" onclick="document.forms[0].submit()">Go</a>'
		html += '</form>'
		html += '<table border="1">\n'
		html += '<tr style="font-weight:bold;">'
		html += '<td>Patch</td>'
		html += '<td>Description</td>'
		html += '</tr>\n'
		
		for patch_id in patch_ids:
			html += '<tr>'
			html += '<td><a href="' + self.problemdb_url + str(patch_id) + '" target="_blank">' + str(patch_id) + '</a></td>'
			patch_desc_file = self.root_path + '/' + str(patch_id) + '/patch_install/fixlist.db'
			if os.path.exists(patch_desc_file):
				content = ''
				f = open(patch_desc_file)
				for line in f:
					content += line
				f.close()
				html +=  '<td><a href="' + self.problemdb_url + str(patch_id) + '" target="_blank">' + content + '</a></td>'
			else:
				html +=  '<td><a href="' + self.problemdb_url + str(patch_id) + '" target="_blank">Unknown</a></td>'
			html += '</tr>\n'
		html += '</table>\n'
		html += '</body>'
		html += '</html>'
		print(html)
		f = open('/home/fkong/share/test.html', 'w')
		f.write(html)
		f.close()

	def get_patch_ids(self):
		patch_ids = []
		for root, dirs, files in os.walk(self.root_path):
			for dir in dirs:
				try:
					patch_ids.append(int(dir))
				except:
					continue
			break
		patch_ids = sorted(patch_ids)
		return patch_ids

	def generate_patch_id_list(self, patch_ids):
		ids = ''
		for patch_id in patch_ids:
			ids += str(patch_id) + ' '
		return ids

pu = PatchUtil()
pu.print_list()
pu.print_html()
